package zuoYe.dao;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class BaseDAO {
    private String user = "root";
    private String password = "root";
    private String driver = "com.mysql.cj.jdbc.Driver";
    private String url = "jdbc:mysql://localhost:3306/hotel_db";

    private Connection connection;
    private PreparedStatement statement;
    private ResultSet set;

    public Connection getConnection() {
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }



    public void allCol2(Connection connection, PreparedStatement statement, ResultSet set) {
        if (set != null) {
            try {
                set.close();
                if (statement != null) {
                    statement.close();
                    if (connection != null) {
                        connection.close();
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    public ResultSet getSet(String sql, Object[] objects) {   //通用查代码
        connection = getConnection();
        if (connection != null) {
            try {
                statement = connection.prepareStatement(sql);
                if (objects != null) {
                    for (int i = 0; i < objects.length; i++) {
                        statement.setObject((i + 1), objects[i]);
                    }
                }
                set = statement.executeQuery();
                return set;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public int getUpdate(String sql, Object[] objects) {   //通用增删改代码
        connection = getConnection();
        if (connection != null) {
            try {
                statement = connection.prepareStatement(sql);
                if (objects != null) {
                    for (int i = 0; i < objects.length; i++) {
                        statement.setObject((i + 1), objects[i]);
                    }
                }
                return statement.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }


}
